<template>
	<view class="container-wrap">
		<!-- 主头部 -->
		<uv-sticky style="background-color:#FAD9CC;">
			<view class="container-wrap-info">
				<view class="topNav" :style="{height:state.navHeight+'px'}" @click="handleLocationClick">
					<view class="nav-left" :style="{paddingTop:state.statusBarHeight+'px'}">
						<image :src="state.address" mode="widthFix" class="addrss-img"></image>
						<view class="city-box">{{state.city || '定位中...'}}</view>
					</view>
				</view>
				<view class="content-search" @click="hanldeSearch">
					<view class="flex-header">
						<view class="flex-header-left">
							<image :src="state.searchText" mode="aspectFill" class="searchText-img"></image>
							<image src="https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/search.png" mode="widthFix"
								class="search-img"></image>
							<view class="line-info"></view>
							<text class="search-text">搜索想要的内容</text>
						</view>
						<view class="flex-header-right">
							搜索
						</view>
					</view>
				</view>
			</view>
		</uv-sticky>


		<!-- 搜索 -->
		<!-- <view class="content-search" @click="hanldeSearch">
			<view class="flex-header">
				<view class="flex-header-left">
					<image :src="state.searchText" mode="aspectFill" class="searchText-img"></image>
					<image src="https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/search.png" mode="widthFix"
						class="search-img"></image>
					<view class="line-info"></view>
					<text class="search-text">搜索想要的内容</text>
				</view>
				<view class="flex-header-right">
					搜索
				</view>
			</view>
		</view> -->
		<!-- 轮播图 -->
		<view class="swiper-wrap">
			<view class="tui-banner-bg">
				<!--banner-->
				<view class="tui-banner-box">
					<uv-swiper   @click="handleSwiper" keyName="image" indicator-color="rgba(255, 255, 255, 0.8)"
						indicator-active-color="#FF7C00" :list="state.banner" indicator indicatorMode="dot"
						circular></uv-swiper>
					<!-- <swiper :indicator-dots="true" :autoplay="true" :interval="5000" :duration="150"
						class="tui-banner-swiper" :circular="true" indicator-color="rgba(255, 255, 255, 0.8)"
						indicator-active-color="#FF7C00">
						<swiper-item v-for="(item, index) in state.banner" @click="handleSwiper(index)" :key="index">
							<image :src="item.image" class="tui-slide-image" mode="scaleToFill" />
						</swiper-item>
					</swiper> -->
				</view>
			</view>
		</view>
		<view class="list-info">
			<uv-scroll-list :indicator="false" indicatorColor="#DDDDDD" indicatorActiveColor="#FF7C00">
				<view class="flex-wrap">
					<view @click="handleType(item,index)" v-for="(item, index) in state.category" :key="index"
						class="flex-item">
						<image :src="item.image" mode="aspectFill" class="list-img"></image>
						<view>{{item.name}}</view>
					</view>
				</view>
			</uv-scroll-list>
		</view>
		<!-- 热门 -->
		<view class="hot-wrap">
			<view class="hot-left">
				<uv-swiper height="240" keyName="image" indicator-color="rgba(255, 255, 255, 0.8)"
					indicator-active-color="#FF7C00" :list="state.bannerList" indicator indicatorMode="dot"
					circular></uv-swiper>
					<!-- <swiper :indicator-dots="true" :autoplay="true" :interval="5000" :duration="150"
					class="tui-banner-swiper-box" :circular="true" indicator-color="rgba(255, 255, 255, 0.8)"
					indicator-active-color="#FF7C00">
					<swiper-item v-for="(item, index) in state.bannerList" :key="index">
						<image :src="item.image" class="tui-image" mode="heightFix" />
					</swiper-item>
				</swiper> -->
			</view>
			<view class="hot-right">
				<view class="hot-top">
					<view class="hot-content">
						<view class="hot-item" @click="goCategory(el.id)" v-for="(el,i) in state.hotList" :key="i">
							<view class="hot-img">
								<image mode="widthFix" class="img-tips" :src="el.image"></image>
							</view>
							<view class="hot-text">{{el.name}}</view>
						</view>

					</view>
				</view>
				<view class="hot-bottom">
					<view class="hot-content">
						<view class="hot-item" @click="goCategory(el.id)" v-for="(el,ind)  of state.categoryList"
							:key="ind">
							<view class="hot-img">
								<image mode="widthFix" class="img-tips" :src="el.image"></image>
							</view>
							<view class="hot-text">{{el.name}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="tab-list">
			<view class="custom-tabs">
				<view class="tabs-container">
					<view class="tab-item" :class="{ 'tab-item-active': state.current === index }"
						v-for="(item, index) in state.tabList" :key="index" @click="tabChange(item, index)">
						<text class="tab-text">{{ item.name }}</text>
					</view>
							<view class="tab-line" :style="{ left: (state.current * 25 + 12.5) + '%', transform: 'translateX(-50%)' }"></view>
				</view>
			</view>
		</view>
		<view class="waterfall-wrap">
			<!-- 加载状态提示框 -->
			<view v-if="state.loadding" class="loading-container">
				<view class="loading-box">
					<view class="loading-icon">
						<text class="loading-text">{{ state.loadingText }}</text>
					</view>
				</view>
			</view>
			
			<!-- 商品列表 -->
			<view v-else-if="state.goodsList.length > 0" class="goods-list">
				<view class="goods-grid">
					<view 
						v-for="item in state.goodsList" 
						:key="item.id" 
						class="goods-item"
						@click="handleItemClick(item)"
					>
						<view class="goods-image">
							<image :src="item.image" mode="aspectFill" class="item-image"></image>
						</view>
						<view class="goods-content">
							<view class="goods-title">
								<text class="title-text">{{ item.title }}</text>
							</view>
							<view class="goods-price">
								<!-- 共富会员：显示VIP价格和原价（划线） -->
								<template v-if="state.userInfo && state.userInfo.level == 2">
									<text class="price-text">￥{{ item.vip_price || (item.price ? item.price[0] : '暂无价格') }}</text>
									<text class="original-price" v-if="item.vip_price && item.original_price">￥{{ item.original_price }}</text>
								</template>

								<!-- 优惠会员：显示VIP价格和原价（划线） -->
								<template v-else-if="state.userInfo && state.userInfo.level == 1">
									<text class="price-text">￥{{ item.vip_price || (item.price ? item.price[0] : '暂无价格') }}</text>
									<text class="original-price" v-if="item.vip_price && item.original_price">￥{{ item.original_price }}</text>
								</template>

								<!-- 注册会员：只显示原价 -->
								<template v-else>
									<text class="price-text">￥{{ item.price ? item.price[0] : '暂无价格' }}</text>
								</template>
							</view>
							<view class="goods-sales">
								<text class="sales-text">已售{{ item.sales }}件</text>
								<view class="bean-info" v-if="item.microbean">
									<image mode="widthFix" :src="state.goldenBean" class="bean-img"></image>
									<text class="bean-text">{{ item.microbean }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<view v-else class="empty-container">
				<view class="empty-box">
					<text class="empty-text">暂无商品数据</text>
				</view>
			</view>
			
			<view class="top-fixed" v-show="state.showBack" @click="goTop">
				<image :src="state.backTop" mode="widthFix" class="backTop-img"></image>
			</view>
		</view>
		<!-- <s-layout
      tabbar="/pages/index/index"
      :bgStyle="template.style?.background"
      :navbarStyle="template.style?.navbar"
      :showLeftButton="false"
    >
		<s-block v-for="(item, index) in template.data" :key="index" :styles="item.style">
		  <s-block-item :type="item.type" :data="item.data" :styles="item.style" />
		</s-block> 

	 </s-layout> -->

		<!-- 城市选择器 -->
		<view v-if="state.cityPickerVisible">
			<cityPicker :visible="state.cityPickerVisible" :column="3" :default-value="state.defaultCityValue"
				:mask-close-able="true" @confirm="onCityConfirm" @cancel="onCityCancel" />
		</view>

	</view>
</template>

<script setup>
	import { computed, reactive, onMounted, ref,nextTick } from 'vue';
	import {
		onLoad,
		onShow,
		onPageScroll,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import $share from '@/sheep/platform/share';
	import carousel from "@/components/czx-carousel/czx-carousel.vue"
	import cityPicker from '@/components/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker.vue'

	const isLogin = computed(() => sheep.$store('user').isLogin);
	const state = reactive({
		tabList: [{
				name: '热门推荐',
				code: 1
			},
			{
				name: '首发新品',
				code: 2
			},
			{
				name: '本地生活',
				code: 3
			},
			{
				name: '活动促销',
				code: 4
			}
		],
		bannerList: [

		],
		banner: [],
		category: [],
		newProduct: [],
		productList: [],
		pageIndex: 1,
		loadding: false,
		pullUpOn: true,
		opacity: 1,
		address: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/address.png',
		searchText: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/searchText.png',
		goldenBean: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/goldenBean.png',
		backTop: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/backTop.png',
		city: '',
		cityPickerVisible: false,
		defaultCityValue: '',
		keyword: '',
		status: 'loadmore',
		iconType: 'flower',
		loadingText: '努力加载中...',
		loadmoreText: '轻轻上拉',
		nomoreText: '没有更多了',
		showBack: false,
		scrollTop: 0,
		current: 0,
		showFixedHeader: false,
		home_tag: 1,
		statusBarHeight: 0,
		navHeight: 0,
		goodsList: [],
		baseUrl: 'https://wei.wemay888.com',
		categoryList: [],
		hotList: [],
		userInfo: {},
		swiperTopMargin: 0 // swiper-wrap距离顶部的高度
	})
	const hanldeSearch = () => {
		// 检查登录状态
		if (!checkLoginStatus()) {
			return
		}
		uni.navigateTo({
			url: '/subPackages/search/search'
		})
	}

	// 处理定位点击
	const handleLocationClick = () => {
		// 检查登录状态
		if (!isLogin.value) {
			uni.showModal({
				title: '温馨提示',
				content: '选择地址功能需要登录后才能使用',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}
		openCityPicker()
	}

	// 选择位置
	const chooseLocation = () => {
		uni.chooseLocation({
			success: (res) => {
				// 更新城市信息
				state.city = res.name || res.address || '未知位置'

				// 显示选择成功提示
				uni.showToast({
					title: '位置已更新',
					icon: 'success',
					duration: 1500
				})
			},
			fail: (err) => {
				uni.showToast({
					title: '选择位置失败',
					icon: 'none'
				})
			}
		})
	}
	onShow(() => {
		
	})

	// 打开城市选择器
	const openCityPicker = () => {
		// 设置默认值，如果有当前城市信息，尝试解析
		if (state.city) {
			// 尝试从当前城市信息中提取省市县
			const reg = /([\u4e00-\u9fa5]+省|自治区|[\u4e00-\u9fa5]+市|[\u4e00-\u9fa5]+区|[\u4e00-\u9fa5]+县)/g;
			const matches = state.city.match(reg);
			if (matches && matches.length >= 2) {
				state.defaultCityValue = matches.slice(0, 3); // 取前三个匹配项
			}
		}
		state.cityPickerVisible = true
	}

	// 手动重新定位
	const reLocation = () => {
		getLocation();
	}


	// 城市选择器确认
	const onCityConfirm = (val) => {
		// val 包含 code 和完整地区名称
		state.city = val.name || val.fullName || '未知位置'
		state.cityPickerVisible = false

		// 显示选择成功提示
		uni.showToast({
			title: '位置已更新',
			icon: 'success',
			duration: 1500
		})
	}

	// 城市选择器取消
	const onCityCancel = () => {
		state.cityPickerVisible = false
	}

	// 轮播图跳转
	const handleSwiper = (index) => {
		// 未登录用户也可以查看轮播图跳转的商品，在加购和购买时再提示登录
		state.banner.map((el, i) => {
			if (i == index) {
				uni.navigateTo({
					url: `/pages/goods/list?categoryId=${el.id}`
				})
			}
		})
	}

	const goLoginInfo = () => {
		uni.navigateTo({
			url: `/subPackages/codeLogin/codeLogin`
		})
	}

	// 跳转到登录页面
	const goToLogin = () => {
		uni.navigateTo({
			url: '/subPackages/login/login'
		})
	}
	// 显示原生tabBar
	uni.showTabBar({
		fail: () => {},
	});
	// 页面滚动距离超过100才显示返回顶部的按钮  
	const tabChange = (item, index) => {
		// 未登录用户也可以切换标签查看不同商品，在加购和购买时再提示登录
		state.current = index
		state.home_tag = item.code
		initList()
	}
	// 跳转分类
	const goCategory = (id) => {
		// 未登录用户也可以查看分类商品，在加购和购买时再提示登录
		uni.navigateTo({
			url: `/pages/goods/list?categoryId=${id}`
		})
	}
	const handleType = (item, index) => {
		// 未登录用户也可以查看分类商品，在加购和购买时再提示登录
		uni.navigateTo({
			url: `/pages/goods/list?categoryId=${item.id}`
		})
		// uni.switchTab({
		// 	url: `/pages/index/category`,
		// 	success:(e)=>{
		// 		uni.$emit('templateClick',item.name,index)
		// 	}
		// })
	}
	const getBarHeight = () => {
		//获取手机系统的信息 里面有状态栏高度和设备型号
		let {
			statusBarHeight,
			system
		} = uni.getSystemInfoSync()
		// 注意返回的单位是px 不是rpx
		state.statusBarHeight = statusBarHeight
		// 而导航栏的高度则 = 状态栏的高度 + 判断机型的值（是ios就+40，否则+44）
		// 这个高度刚好和胶囊对齐
		state.navHeight = statusBarHeight + (system.indexOf('iOS') > -1 ? 40 : 44)
	}

	// 计算swiper-wrap距离顶部的高度
	const calculateSwiperTopMargin = () => {
		// 直接设置轮播图距离顶部背景20rpx
		state.swiperTopMargin = 20

		console.log('轮播图距离顶部:', state.swiperTopMargin + 'rpx')
	}
	const template = computed(() => sheep.$store('app').template?.home);

	// 检查登录状态 - 点击操作时检查
	const checkLoginStatus = () => {
		if (!isLogin.value) {
			console.log('用户未登录，跳转到登录页面')
			
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return false
		}
		console.log('用户已登录，继续操作')
		return true
	}

	// 控制微信分享功能
	const controlShareMenu = () => {
		// #ifdef MP-WEIXIN
		if (isLogin.value) {
			// 已登录用户，显示分享按钮
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
		} else {
			// 未登录用户，隐藏分享按钮
			wx.hideShareMenu({
				menus: ['shareAppMessage', 'shareTimeline']
			})
		}
		// #endif
	}

	// 处理微信分享
	const onShareAppMessage = () => {
		// #ifdef MP-WEIXIN
		// 检查登录状态
		if (!isLogin.value) {
			// 未登录用户
			uni.showModal({
				title: '温馨提示',
				content: '转发分享请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			// 阻止分享的多种方法
			return {
				title: '',
				path: '',
				imageUrl: ''
			}
		} else {
			// 已登录用户，允许分享
			// 获取当前用户的邀请码
			let inviteCode = '';
			if (state.userInfo && state.userInfo.invite_code) {
				inviteCode = state.userInfo.invite_code;
			}
			
			// 构建分享路径，包含邀请码参数
			let sharePath = '/subPackages/codeLogin/codeLogin';
			if (inviteCode) {
				sharePath += `?invite_code=${inviteCode}`;
			}
			
			return {
				title: '邀请好友注册',
				path: sharePath,
				imageUrl: ''
			}
		}
		// #endif
	}

	onLoad((options) => {
		getBarHeight()
		calculateSwiperTopMargin() // 计算swiper-wrap距离顶部的高度
		
		// 控制微信分享功能
		// #ifdef MP-WEIXIN
		// 根据登录状态控制分享功能
		controlShareMenu()
		// #endif
		
		// #ifdef MP
		// 小程序识别二维码
		if (options.scene) {
			const sceneParams = decodeURIComponent(options.scene).split('=');
			options[sceneParams[0]] = sceneParams[1];
		}
		// #endif
		// 预览模板
		if (options.templateId) {
			sheep.$store('app').init(options.templateId);
		}

		// 解析分享信息
		if (options.spm) {
			$share.decryptSpm(options.spm);
		}

		// 进入指定页面(完整页面路径)
		if (options.page) {
			sheep.$router.go(decodeURIComponent(options.page));
		}

	})

	// 监听登录状态变化
	onShow(() => {
		// 每次页面显示时检查登录状态并更新用户信息
		checkAndUpdateUserInfo()
		
		// 控制微信分享功能
		// #ifdef MP-WEIXIN
		// 根据登录状态控制分享功能
		controlShareMenu()
		// #endif
	})
	const getUserInfo = async () => {
		try {
			// 检查是否已登录
			const isLogin = sheep.$store('user').isLogin;
			if (isLogin) {
				const userInfo = await sheep.$store('user').getInfo();
				state.userInfo = userInfo || {};
				console.log('获取到用户信息:', state.userInfo)
			} else {
				// 未登录时设置默认值
				state.userInfo = {
					level: 0,
					level_text: '普通用户'
				};
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			// 出错时设置默认值
			state.userInfo = {
				level: 0,
				level_text: '普通用户'
			};
		}
	};

	// 检查并更新用户信息
	const checkAndUpdateUserInfo = async () => {
		const currentLoginStatus = sheep.$store('user').isLogin;
		const currentUserLevel = state.userInfo?.level || 0;

		// 如果登录状态发生变化，或者用户信息不完整，则重新获取
		if (currentLoginStatus && (!state.userInfo || !state.userInfo.level)) {
			console.log('检测到登录状态变化，更新用户信息')
			await getUserInfo()
			// 如果用户是VIP，重新加载商品列表以显示VIP价格
			if (state.userInfo.level == 2) {
				console.log('检测到VIP用户，重新加载商品列表')
				await initList()
			}
		} else if (!currentLoginStatus && currentUserLevel > 0) {
			// 如果用户登出，重置用户信息
			console.log('检测到用户登出，重置用户信息')
			state.userInfo = {
				level: 0,
				level_text: '普通用户'
			}
			// 重新加载商品列表以显示普通价格
			await initList()
		}
		
		// 根据登录状态控制分享功能
		// #ifdef MP-WEIXIN
		controlShareMenu()
		// #endif
	}

	const handleItemClick = (item) => {
		console.log(item, '参数哈哈哈')
		// 未登录用户也可以查看商品详情，在加购和购买时再提示登录
		let { id } = item
		uni.navigateTo({
			url: `/subPackages/goods/index?id=${id}`
		})
	}
	onMounted(() => {
		console.log(isLogin.value, '是否登录')
		// 未登录用户也可以看到页面内容
		init()

		// 监听登录状态变化事件
		uni.$on('loginStatusChanged', () => {
			console.log('收到登录状态变化事件，更新用户信息')
			checkAndUpdateUserInfo()
		})

		// 监听位置选择事件
		uni.$on('locationSelected', (locationData) => {
			// 更新城市信息
			state.city = locationData.name || locationData.address || '未知位置'

			// 显示选择成功提示
			uni.showToast({
				title: '位置已更新',
				icon: 'success',
				duration: 1500
			})

			// 这里可以保存选择的位置信息到本地存储或发送到服务器
			// uni.setStorageSync('selectedLocation', locationData)
		})
	})
	const init = async () => {
		await getUserInfo()
		await initData()
		await initList()
		await getLocation() //获取定位信息
		await getBannerData() //轮播图数据
		await getSmallBannerData() //小轮博图
		await initDataList()
	}
	// 定位信息
	const getLocation = () => {
		uni.getLocation({
			type: 'gcj02',
			success: (res) => {
				console.log('定位成功:', res);
				state.city = '定位中...';

				// 调用API获取地址信息
				let params = {
					lng: res.longitude,
					lat: res.latitude
				}

				sheep.$api.user.locationInfo(params).then(({ code, data }) => {
					if (code == 1) {
						state.city = data.address;
					} else {
						state.city = '定位失败';
					}
				}).catch(() => {
					state.city = '定位失败';
				});
			},
			fail: (err) => {
				console.log('定位失败:', err);
				state.city = '定位失败';
			}
		});
	}

	// 小轮播图
	const getSmallBannerData = async () => {
		try {
			let params = {
				type: 'main'
			}
			const { code, data } = await sheep.$api.login.getSmallBannerList({});
			if (code == 1) {
				state.bannerList = data.banners.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
			} else {
				console.log('加载小轮播图失败:', data?.msg || '未知错误')
				if (!isLogin.value) {
					state.bannerList = []
				}
			}
		} catch (error) {
			console.log('小轮播图加载异常:', error)
			if (!isLogin.value) {
				state.bannerList = []
			}
		}
	}
	// 大轮播图
	const getBannerData = async () => {
		try {
			let params = {
				type: 'main'
			}
			const { code, data } = await sheep.$api.login.getBanner(params);
			if (code == 1) {
				state.banner = data.banners.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
			} else {
				console.log('加载轮播图失败:', data?.msg || '未知错误')
				// 未登录用户清空轮播图
				if (!isLogin.value) {
					state.banner = []
				}
			}
		} catch (error) {
			console.log('轮播图加载异常:', error)
			if (!isLogin.value) {
				state.banner = []
			}
		}
	}
	const initList = async () => {
		try {
			// 开始加载，显示加载提示框
			state.loadding = true
			
			let params = {
				home_tag: state.home_tag
			}

			// 尝试加载数据，如果失败（比如未登录），显示基础数据
			const { code, data } = await sheep.$api.login.goodsList(params);

			if (code == 1) {
				state.goodsList = data.data.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
			} else {
				// 如果API调用失败，可能是未登录或网络问题
				// 可以在这里加载一些基础商品数据或者空状态
				console.log('加载商品列表失败:', data?.msg || '未知错误')
				if (!isLogin.value) {
					console.log('用户未登录，使用基础商品数据')
					// 这里可以加载一些不需要登录就能看到的商品
					state.goodsList = []
				}
			}
		} catch (error) {
			console.log('商品列表加载异常:', error)
			// 网络错误时也清空列表
			if (!isLogin.value) {
				state.goodsList = []
			}
		} finally {
			// 加载完成，隐藏加载提示框
			state.loadding = false
		}
	}
	const initData = async () => {
		try {
			const { code, data } = await sheep.$api.login.categoryList();
			if (code == 1) {
				state.category = data.children.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
			} else {
				console.log('加载分类失败:', data?.msg || '未知错误')
				// 未登录用户看不到分类数据
				if (!isLogin.value) {
					state.category = []
				}
			}
		} catch (error) {
			console.log('分类加载异常:', error)
			if (!isLogin.value) {
				state.category = []
			}
		}
	}
	const initDataList = async () => {
		try {
			let params = {
				id: 154
			}
			const { code, data } = await sheep.$api.login.categoryList(params);
			if (code == 1) {
				state.categoryList = data.children[0].children[0].children.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
				state.hotList = data.children[0].children[1].children.map(el => {
					el.image = `${state.baseUrl}${el.image}`
					return el
				})
			} else {
				console.log('加载详细分类失败:', data?.msg || '未知错误')
				if (!isLogin.value) {
					state.categoryList = []
					state.hotList = []
				}
			}
		} catch (error) {
			console.log('详细分类加载异常:', error)
			if (!isLogin.value) {
				state.categoryList = []
				state.hotList = []
			}
		}
	}


	// 下拉刷新
	onPullDownRefresh(() => {
		sheep.$store('app').init();
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 800);
	});
	// 页面滚动监听
	onPageScroll((ev) => {
		// 当滚动距离超过200px时显示固定头部
		if (ev.scrollTop > 200) {
			state.showFixedHeader = true;
		} else {
			state.showFixedHeader = false;
		}

		// 当滚动距离超过300px时显示返回顶部按钮
		if (ev.scrollTop > 300) {
			state.showBack = true;
		} else {
			state.showBack = false;
		}

		state.scrollTop = ev.scrollTop;
	});

	// 返回顶部方法
	const goTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		});
	};

</script>

<style lang="scss" scoped>
	@import 'index.scss'
</style>